import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QHBoxLayout, QVBoxLayout,
    QPushButton, QLabel, QFrame, QSizePolicy, QFileDialog, QTextEdit, QDialog
)
from PyQt5.QtCore import Qt, QPropertyAnimation, QEasingCurve
from PyQt5.QtGui import QPixmap, QImage, QFont
import cv2
from PIL import  Image
import numpy as np
from detect import handle_picture,count_num
from PyQt5.QtCore import QThread, pyqtSignal, QTimer

class Ui_Form:
    def setupUi(self, Form):
        Form.resize(1300, 800)  # 增加窗口大小以容纳结果显示区域
        Form.setStyleSheet("""
            QWidget {
                background-color: #f5f6fa;
                font-family: "Segoe UI", sans-serif;
                font-size: 14px;
            }
            QPushButton {
                background-color: #3f51b5;
                color: white;
                border-radius: 8px;
                padding: 10px;
                font-size: 16px;
                min-height: 40px;
            }
            QPushButton:hover {
                background-color: #303f9f;
            }
            QLabel {
                background-color: #ffffff;
                border-radius: 10px;
                border: 2px solid #dcdde1;
                padding: 5px;
            }
            QFrame#separator {
                background-color: #dcdde1;
            }
            #sidebar, #btnContainer {
                background-color: #2f3640;
            }
            QTextEdit {
                background-color: #ffffff;
                border-radius: 10px;
                border: 2px solid #dcdde1;
                padding: 10px;
                font-size: 14px;
            }
            .result-label {
                font-weight: bold;
                font-size: 16px;
                color: #2f3640;
                background-color: #e1f5fe;
                border-radius: 8px;
                padding: 8px;
                border: 1px solid #b3e5fc;
            }
            .count-display {
                font-size: 24px;
                font-weight: bold;
                color: #3f51b5;
                background-color: rgba(255, 255, 255, 0.7);
                border-radius: 5px;
                padding: 2px 8px;
            }
        """)

        # 主窗口布局
        self.main_layout = QHBoxLayout(Form)
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)

        # ====== 左侧侧边栏（可滑动）======
        self.sidebar = QWidget()
        self.sidebar.setObjectName("sidebar")
        self.sidebar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.sidebar.setMinimumWidth(40)
        self.sidebar.setMaximumWidth(200)

        sidebar_layout = QVBoxLayout(self.sidebar)
        sidebar_layout.setSpacing(10)
        sidebar_layout.setContentsMargins(5, 20, 5, 20)

        self.btn_toggle_sidebar = QPushButton("⬅️ 收起")
        self.btn_toggle_sidebar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        # 创建按钮容器
        self.btn_container = QWidget()
        self.btn_container.setObjectName("btnContainer")
        btn_container_layout = QVBoxLayout(self.btn_container)
        btn_container_layout.setContentsMargins(0, 0, 0, 0)
        btn_container_layout.setSpacing(10)
        
        self.btn_open = QPushButton("📁 打开图像")
        self.btn_process = QPushButton("🔍 天牛检测")
        self.btn_generate = QPushButton("📊 图像生成")
        
        btn_container_layout.addWidget(self.btn_open)
        btn_container_layout.addWidget(self.btn_process)
        btn_container_layout.addWidget(self.btn_generate)
        
        sidebar_layout.addWidget(self.btn_toggle_sidebar)
        sidebar_layout.addWidget(self.btn_container)
        sidebar_layout.addStretch()

        # ====== 分割线 ======
        self.separator = QFrame()
        self.separator.setObjectName("separator")
        self.separator.setFixedWidth(4)

        # ====== 右侧内容区域 ======
        content_widget = QWidget()
        content_layout = QVBoxLayout(content_widget)

        # 图像显示区域
        image_layout = QHBoxLayout()
        image_layout.setSpacing(20)
        image_layout.setContentsMargins(20, 20, 20, 10)  # 调整边距

        # 原始图像区域
        original_frame = QVBoxLayout()
        original_frame.setSpacing(10)
        self.label_original_title = QLabel("原始图像")
        self.label_original_title.setAlignment(Qt.AlignCenter)
        self.label_original_title.setStyleSheet("font-weight: bold; font-size: 16px; color: #3f51b5;")
        self.label_original_title.setMaximumHeight(60)  # 设置标题最大高度
        
        self.label_original = QLabel()
        self.label_original.setAlignment(Qt.AlignCenter)
        self.label_original.setMinimumSize(400, 300)
        
        # 添加示例图像
        self.label_original.setText("请加载图像")
        self.label_original.setStyleSheet("font-style: italic; color: #7f8c8d;")
        
        original_frame.addWidget(self.label_original_title)
        original_frame.addWidget(self.label_original)

        # 处理后图像区域
        processed_frame = QVBoxLayout()
        processed_frame.setSpacing(10)
        self.label_processed_title = QLabel("检测结果")
        self.label_processed_title.setAlignment(Qt.AlignCenter)
        self.label_processed_title.setStyleSheet("font-weight: bold; font-size: 16px; color: #3f51b5;")
        self.label_processed_title.setMaximumHeight(60)
        
        self.label_processed = QLabel()
        self.label_processed.setAlignment(Qt.AlignCenter)
        self.label_processed.setMinimumSize(400, 300)
        
        # 添加示例计数显示
        self.count_display = QLabel("检测目标: 0")
        self.count_display.setAlignment(Qt.AlignCenter)
        self.count_display.setStyleSheet(".count-display")
        self.count_display.setFixedHeight(40)
        
        processed_frame.addWidget(self.label_processed_title)
        processed_frame.addWidget(self.label_processed)
        processed_frame.addWidget(self.count_display)

        image_layout.addLayout(original_frame, stretch=1)
        image_layout.addLayout(processed_frame, stretch=1)

        content_layout.addLayout(image_layout, stretch=2)  # 图像区域占2份空间

        # ====== 结果显示区域 ======
        result_layout = QVBoxLayout()
        result_layout.setContentsMargins(20, 10, 20, 20)
        result_layout.setSpacing(10)
        
        result_title = QLabel("检测结果统计")
        result_title.setStyleSheet("font-weight: bold; font-size: 18px; color: #2f3640;")
        result_title.setAlignment(Qt.AlignCenter)
        
        # 结果统计信息
        stats_layout = QHBoxLayout()
        stats_layout.setSpacing(15)
        
        # 详细结果文本框
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        self.result_text.setPlaceholderText("检测结果将显示在这里...")
        self.result_text.setFont(QFont("Consolas", 10))
        
        # 添加示例结果
        self.result_text.setPlainText(
            "=== 欢迎使用天牛计数系统！！！ ===\n"
            "请上传天牛图片 \n"
        )
        
        result_layout.addWidget(result_title)
        result_layout.addLayout(stats_layout)
        result_layout.addWidget(self.result_text, stretch=1)
        
        content_layout.addLayout(result_layout, stretch=1)  # 结果区域占1份空间

        # 将组件添加到主布局中
        self.main_layout.addWidget(self.sidebar)
        self.main_layout.addWidget(self.separator)
        self.main_layout.addWidget(content_widget)

        # ===== 动画初始化 =====
        self.sidebar_animation = QPropertyAnimation(self.sidebar, b"minimumWidth")
        self.sidebar_animation.setDuration(300)
        self.sidebar_animation.setEasingCurve(QEasingCurve.InOutQuart)
        
        self.sidebar_animation2 = QPropertyAnimation(self.sidebar, b"maximumWidth")
        self.sidebar_animation2.setDuration(300)
        self.sidebar_animation2.setEasingCurve(QEasingCurve.InOutQuart)

        self.is_sidebar_expanded = True  # 初始状态为展开

    def toggle_sidebar(self):
        if self.is_sidebar_expanded:
            # 收起侧边栏，但保留40px宽度确保按钮可见
            self.sidebar_animation.setStartValue(200)
            self.sidebar_animation.setEndValue(40)
            self.sidebar_animation2.setStartValue(200)
            self.sidebar_animation2.setEndValue(40)
            self.btn_toggle_sidebar.setText("→")  # 只显示箭头
            # 隐藏其他按钮
            self.btn_container.hide()
        else:
            # 展开侧边栏
            self.sidebar_animation.setStartValue(40)
            self.sidebar_animation.setEndValue(200)
            self.sidebar_animation2.setStartValue(40)
            self.sidebar_animation2.setEndValue(200)
            self.btn_toggle_sidebar.setText("⬅️ 收起")
            # 显示其他按钮
            self.btn_container.show()

        self.is_sidebar_expanded = not self.is_sidebar_expanded
        self.sidebar_animation.start()
        self.sidebar_animation2.start()

class ImageProcessingThread(QThread):
    log_signal = pyqtSignal(str)  # 发送日志信息
    result_ready = pyqtSignal(str, str)  # 处理后的图片路径和计数结果

    def __init__(self, image_path):
        super().__init__()
        self.image_path = image_path

    def run(self):
        """在子线程中运行"""
        self.log_signal.emit("正在进行检测，请耐心等待......\n")
        
        # 模拟耗时操作，替换为实际的 handle_picture 和 count_num 函数
        processed_image_path = handle_picture(self.image_path)
        result = count_num(self.image_path)

        self.log_signal.emit("图像处理完成。\n")
        self.result_ready.emit(processed_image_path, result)

# 实现图像生成的子窗口
class SubWindow(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("重叠图像生成")
        self.setGeometry(400, 200, 300, 200)
        
        layout = QVBoxLayout()
        
        self.label = QLabel("功能暂未实现", self)
        self.button = QPushButton("关闭", self)
        self.button.clicked.connect(self.close)
        layout.addWidget(self.label)
        layout.addWidget(self.button)
        
        self.setLayout(layout)


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setWindowTitle("天牛计数系统")

        self.img_dir = ""
        self.img = None
        self.new_img = None

        # 连接按钮事件
        self.ui.btn_toggle_sidebar.clicked.connect(self.ui.toggle_sidebar)
        self.ui.btn_open.clicked.connect(self.open_image)
        self.ui.btn_process.clicked.connect(self.process_image)
        self.ui.btn_generate.clicked.connect(self.generate_image)

    def generate_image(self):
        """生成图像的占位符函数"""
        self.ui.result_text.append("图像生成功能尚未实现。\n")
        # 添加实际的图像生成逻辑
        sub_window = SubWindow()
        sub_window.exec_() 

    def CV2Qt(self, img):
        # 获取原始图像尺寸
        original_height, original_width, channel = img.shape
        line = original_width * channel

        # 图片格式转化
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        qt_img = QImage(img.data, original_width, original_height, line, QImage.Format_RGB888)
        qt_img = QPixmap.fromImage(qt_img)

        # 图片缩放
        qt_img = qt_img.scaled(self.ui.label_original.size(), Qt.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
        return qt_img


    def open_image(self):
        try:
            self.img_dir = QFileDialog.getOpenFileName(self, "选择图片", ".", "图片文件(*.png *.jpg *.bmp *.tif)")[0]
            image = Image.open(self.img_dir).convert("RGB")
            self.img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
            self.ui.result_text.append(f"已选择图片: {self.img_dir}\n")
        except Exception as e:
            print(f"选择图片失败: {e}")
            return
        qt_img = self.CV2Qt(self.img)
        try:
            self.ui.label_original.setPixmap(qt_img)
        except Exception as e:
            self.ui.label_original.setText("图片加载失败")

    def process_image(self):
        if not self.img_dir:
            self.ui.label_processed.setText("请先选择图片")
            return
        
        # 启动后台线程处理图片
        self.thread = ImageProcessingThread(self.img_dir)
        self.thread.log_signal.connect(self.update_log)
        self.thread.result_ready.connect(self.handle_result)
        self.thread.start()
    def update_log(self, message):
        """更新日志信息"""
        self.ui.result_text.append(message)

    def handle_result(self, processed_image_path, result):
        """处理完成后更新UI"""
        try:
            image = Image.open(processed_image_path).convert("RGB")
            self.new_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
            qt_img = self.CV2Qt(self.new_img)
            self.ui.label_processed.setPixmap(qt_img)
            self.ui.count_display.setText(result)  # 更新计数显示
            self.ui.result_text.append(f"{result}\n")
        except Exception as e:
            print(f"处理图片失败: {e}")
            self.ui.label_processed.setText("处理图片失败")



if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())